package Subject;

import java.util.HashMap;
import java.util.Map;

/**
 * 难度：简单
 * 
 * 290. 单词规律
 * 	给定一种规律 pattern 和一个字符串 str ，判断 str 是否遵循相同的规律。
 * 	这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
 * 
 * 示例1:
 * 	输入: pattern = "abba", str = "dog cat cat dog"
 * 	输出: true
 * 示例 2:
 * 	输入:pattern = "abba", str = "dog cat cat fish"
 * 	输出: false
 * 示例 3:
 * 	输入: pattern = "aaaa", str = "dog cat cat dog"
 * 	输出: false
 * 示例 4:
 * 	输入: pattern = "abba", str = "dog dog dog dog"
 * 	输出: false
 * 
 * 说明:
 * 	你可以假设 pattern 只包含小写字母， str 包含了由单个空格分隔的小写字母。 
 *
 * */

public class WordPattern {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		WordPattern wp = new WordPattern();
		System.out.println(wp.wordPattern1("abba", "dog dog dog dog"));
	}

	public boolean wordPattern(String pattern,String str) {
		
		char[] charArray = pattern.toCharArray();
		String[] split = str.split(" ");
		if(charArray.length!=split.length) {
			return false;
		}
		//保存规律
		Map<Character, Integer> map1 = new HashMap<>();
		int[] cp=new int[pattern.length()];
		for(int i=0;i<charArray.length;i++) {
			if(!map1.containsKey(charArray[i])) {
				map1.put(charArray[i], i);
			}
			cp[i]=map1.get(charArray[i]);
		}
		//比对规律
		Map<String, Integer> map2 = new HashMap<>();
		for(int i=0;i<split.length;i++) {
			if(!map2.containsKey(split[i])) {
				map2.put(split[i], i);
			}
			if(map2.get(split[i])!=(cp[i])) {
				return false;
			}
		}
		return true;
	}
	//方法一：哈希表(未看)
	public boolean wordPattern1(String pattern, String str) {
        Map<String, Character> str2ch = new HashMap<String, Character>();
        Map<Character, String> ch2str = new HashMap<Character, String>();
        int m = str.length();
        int i = 0;
        for (int p = 0; p < pattern.length(); ++p) {
            char ch = pattern.charAt(p);
            if (i >= m) {
                return false;
            }
            //取出单词
            int j = i;
            while (j < m && str.charAt(j) != ' ') {
                j++;
            }
            String tmp = str.substring(i, j);
            //判断单词是否对应字母
            System.out.println(str2ch.containsKey(tmp) +","+ str2ch.get(tmp));
            if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) {
                return false;
            }
            //判断字母是否对应单词
            System.out.println(ch2str.containsKey(ch)+","+(!tmp.equals(ch2str.get(ch))));
            if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) {
                return false;
            }
            str2ch.put(tmp, ch);
            ch2str.put(ch, tmp);
            i = j + 1;
        }
        return i >= m;
    }
}
